<?php

namespace App\Http\Controllers\Api\V1;

use App\Http\Controllers\Api\ApiController;
use Illuminate\Http\Request;
use JWTAuth;
use Illuminate\Support\Facades\Validator;
use Tymon\JWTAuth\Exceptions\JWTException;
use Tymon\JWTAuth\Exceptions\TokenInvalidException;
use Auth;
use App\User;
use Passport;

class AuthenticateController extends ApiController
{
    protected $login = false;

    //登录获取token
    public function authenticate(Request $request)
    {   

        // grab credentials from the request
        $credentials = $request->intersect('phone', 'password', 'open_id', 'code', 'avatar', 'union_id', 'nickname');

        try {
           if (!Auth::attempt($credentials)) {
                // 认证不通过...
                return parent::error('登陆失败,账号或密码错误');
            }
            
            // attempt to verify the credentials and create a token for the user
            if (! $token = JWTAuth::fromUser(Auth::user())) {
                return parent::error('invalid_credentials');
            }
        } catch (JWTException $e) {
            // something went wrong whilst attempting to encode the token
            return parent::error('could_not_create_token');
        } catch(\Exception $e){
            return parent::error($e->getMessage());
        }

        // all good so return the token
        return parent::success('success', [
            'token'       => $token,
            'ttl'         => time() + config('jwt.ttl')*60,//token有效期（秒）
            'refresh_ttl' => time() + config('jwt.refresh_ttl')*60,//刷新token时间（秒）
            'user'        => JWTAuth::authenticate($token),
        ]);
    }

    //重新获取token
    public function refreshToken()
    {   
        try{
            $token = JWTAuth::refresh(JWTAuth::getToken());

            return parent::success('success', [
                'token' => $token,
                'ttl' => time() + config('jwt.ttl')*60,
            ]);
        }catch(TokenInvalidException $e){
            return parent::error('无效的Token');
        }catch(JWTException $e){
            return parent::error('更新失败');
        }
    }

  
}